package com.changgou.pay;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.service.WxPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-25 22:22
 */
@RestController
@RequestMapping("/wxpay")
public class WxPayController {


    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 生成订单支付的二维码
     * @param parameterMap
     * @return
     */
    @GetMapping("/nativePay")
    public Result nativePay(@RequestParam Map<String,String> parameterMap){
        Map map = wxPayService.nativePay(parameterMap);
        return new Result(true, StatusCode.OK,"二维码生成成功",map);
    }

    /**
     * 支付状态查询
     * @param parameterMap
     * @return
     */
    @GetMapping("/queryOrder")
    public Result queryOrder(@RequestParam Map<String,String> parameterMap){
        Map map = wxPayService.queryOrderPay(parameterMap);
        return new Result(true,StatusCode.OK,"订单状态查询成功",map);
    }


    /**
     * 支付结果通知回调方法
     * @param request
     * @return
     */
    @RequestMapping("/notifyurl/url")
    public String notifyurl(HttpServletRequest request) throws Exception{
        //获取网络输入流
        ServletInputStream is = request.getInputStream();

        String result = ConvertUtils.convertToString(is);
        Map<String, String> resultMap = WXPayUtil.xmlToMap(result);

        //将返回的数据传输到队列中
        rabbitTemplate.convertAndSend("exchange.order","queue.order", JSON.toJSONString(resultMap));
        return result;
    }


    /**
     * 关闭微信支付订单
     * @param orderId
     * @return
     */
    @PutMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable String orderId){
        Map map = wxPayService.closeOrder(orderId);
        return new Result(true,StatusCode.OK,"微信订单关闭成功",map);
    }
}
